package test;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class MusicDownloaderClient {
    public static void main(String[] args) {
        try {
            // 创建客户端Socket连接到服务器
            Socket socket = new Socket("localhost", 8888);

            // 获取输入输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

            // 读取用户输入的搜索关键字
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入要搜索的音乐关键字：");
            String keyword = scanner.nextLine();

            // 将用户输入的关键字发送给服务器
            writer.println(keyword);

            // 获取服务器返回的搜索结果
            String response = reader.readLine();
            System.out.println("搜索结果：" + response);

            // 读取用户输入的要下载的音乐文件名
            System.out.print("请输入要下载的音乐文件名：");
            String fileName = scanner.nextLine();

            // 将用户输入的文件名发送给服务器
            writer.println(fileName);
            socket.shutdownOutput();

            // 读取服务器返回的文件内容并保存到本地
            String filePath = "D:\\aaa\\" + fileName;  // 新的指定目录的路径
            System.out.println(filePath);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
            BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            fileOutputStream.close();

            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
